package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.RemainingTimes;
import com.tanhua.domain.mongo.Sound;
import com.tanhua.dubbo.api.mongo.SoundApi;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.Random;

@Service
public class SoundApiImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveSound(Sound sound) {
        mongoTemplate.save(sound);
    }

    /**
     * @param times  用户获取语音的次数
     * @param userId 用户id
     */
    @Override
    public Sound getSound(Integer times, Long userId, String gender) {
        Query query = new Query(Criteria.where("state").is(0).and("userId").ne(userId).and("gender").is(gender));
        List<Sound> soundList = mongoTemplate.find(query, Sound.class);
        Sound sound = null;
        if (soundList != null && soundList.size() > 0) {
            int size = soundList.size();
            Random random = new Random();
            int randomIndex = size == 1 ? 0 : random.nextInt(size - 1);
            sound = soundList.get(randomIndex);
            sound.setState(1L);
            mongoTemplate.save(sound);
        }
        return sound;
    }
}
